//
//  HTTPHelper_topic.m
//  cookBook
//
//  Created by xalo on 16/1/25.
//  Copyright © 2016年 张广斌. All rights reserved.
//

#import "HTTPHelper_topic.h"
#import <AFNetworking.h>
#import "Model.h"
@interface HTTPHelper_topic ()

@end




@implementation HTTPHelper_topic

//单例
+(HTTPHelper_topic *)shareHelper
{
    static HTTPHelper_topic *helper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        helper = [[HTTPHelper_topic alloc] init];
    });
    return helper;
}

//获取网络数据
-(void)fetchTopicListWithUrl:(NSString *)urlStr block:(Block)block
{
    
    //异步请求网络数据
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        
        [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //根据解析出来的responeseObject,找出所需要的model元素,并存入数组
            
            //1.根据键找出对应的数组元素
            NSArray *topicArray = responseObject[@"results"];
            
            //2.遍历topicArray
            for (NSDictionary *dic in topicArray) {
                
                //3.创建model,并将字典dic转model
                Model *model = [[Model alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                
                //4.将model添加到model数组中
                [self.topicListArray addObject:model];
                
            }
            
            block();//主线程刷新数据
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           
            NSLog(@"出错了%@",error);
            
        }];
        
        
    });
    
}

//懒加载
-(NSMutableArray *)topicListArray
{
    if (_topicListArray == nil) {
        _topicListArray = [NSMutableArray array];
    }
    
    return _topicListArray;

}

//数组个数
-(NSInteger)countOfTopicListArray
{
    return self.topicListArray.count;
}
//数组下标index对应的model
-(Model *)returnModelWithIndex:(NSInteger)index
{
    return self.topicListArray[index];
}


@end
